package repository

import (
	"boy-go/modules/system/model"
	"boy-go/modules/system/vo"
	"boy-go/pkg/db"
	"boy-go/pkg/request"
	"fmt"
	"gorm.io/gorm"
	"time"
)

type SysMenuRepository struct {
	DB *gorm.DB
}

func NewSysMenuRepository() *SysMenuRepository {
	return &SysMenuRepository{
		DB: db.GetMasterDB(),
	}
}
func (r *SysMenuRepository) GetById(menuId int64) (*model.SysMenu, error) {
	db := r.DB
	m := &model.SysMenu{}
	err := db.Model(&model.SysMenu{}).Where("menu_id = ?", menuId).First(m).Error
	if err != nil {
		return nil, err
	}
	return m, nil
}

func (r *SysMenuRepository) List(query *vo.QuerySysMenuReq, pageReq *request.PageRequest) ([]*model.SysMenu, int64, error) {
	tx := r.DB.Model(&model.SysMenu{})
	var total int64
	if err := tx.Count(&total).Error; err != nil {
		return nil, 0, err
	}

	list := make([]*model.SysMenu, 0)
	if query != nil {

	}
	if pageReq != nil {
		if total > 0 {
			tx := db.BuildPageAndOrder(tx, pageReq, "parent_id, order_num")
			if err := tx.Select("*").Find(&list).Error; err != nil {
				return nil, total, err
			}
		}
	} else {
		if err := tx.Select("*").Order("parent_id, order_num").Find(&list).Error; err != nil {
			return nil, total, err
		}
	}

	return list, total, nil
}

// Save 添加
func (r *SysMenuRepository) Save(m *model.SysMenu) error {
	currentTime := time.Now()
	m.CreateAt = &currentTime
	return r.DB.Model(&model.SysMenu{}).Create(m).Error
}

// Update 更新
func (r *SysMenuRepository) Update(m *model.SysMenu) error {
	currentTime := time.Now()
	m.UpdateAt = &currentTime
	return r.DB.Model(&model.SysMenu{}).Where("menu_id = ?", m.MenuId).Updates(m).Error
}

// Delete 删除
func (r *SysMenuRepository) Delete(menuId int64) error {
	return r.DB.Model(&model.SysMenu{}).Where("menu_id = ?", menuId).Delete(&model.SysMenu{}).Error
}

// DeleteBatch 批量删除
func (r *SysMenuRepository) DeleteBatch(ids []interface{}) error {
	db := r.DB
	db = db.Where("(menu_id)", ids)
	return db.Delete(&model.SysMenu{}).Error
}
func (r *SysMenuRepository) SelectMenuTreeAll() ([]*model.SysMenu, error) {
	sql := "select distinct m.menu_id, m.parent_id, m.menu_name, m.path, m.component, m.`query`, m.route_name, m.visible, m.status, ifnull(m.perms,'') as perms, m.is_frame, m.is_cache, m.menu_type, m.icon, m.order_num, m.create_time from sys_menu m where m.menu_type in ('M', 'C') and m.status = 0 order by m.parent_id, m.order_num"
	db := r.DB.Raw(sql)
	menus := make([]*model.SysMenu, 0)
	err := db.Find(&menus).Error
	return menus, err
}
func (r *SysMenuRepository) SelectMenuListByUserId(userId int64) ([]*model.SysMenu, error) {
	sql := "select distinct m.menu_id, m.parent_id, m.menu_name, m.path, m.component, m.`query`, m.route_name, m.visible, m.status, ifnull(m.perms,'') as perms, m.is_frame, m.is_cache, m.menu_type, m.icon, m.order_num, m.create_time" +
		" from sys_menu m" +
		" left join sys_role_menu rm on m.menu_id = rm.menu_id" +
		" left join sys_user_role ur on rm.role_id = ur.role_id" +
		" left join sys_role ro on ur.role_id = ro.role_id" +
		" where ur.user_id = " + fmt.Sprintf("%d", userId)
	db := r.DB.Raw(sql)
	menus := make([]*model.SysMenu, 0)
	err := db.Find(&menus).Error
	return menus, err
}

func (r *SysMenuRepository) SelectMenuListByRoleId(roleId int64, menuCheckStrictly bool) ([]*int64, error) {
	sql := "select m.menu_id from sys_menu m left join sys_role_menu rm on m.menu_id = rm.menu_id where rm.role_id = " + fmt.Sprintf("%d", roleId)
	if menuCheckStrictly == true {
		sql += " and m.menu_id not in (select m.parent_id from sys_menu m inner join sys_role_menu rm on m.menu_id = rm.menu_id and rm.role_id = " + fmt.Sprintf("%d", roleId) + ")"
	}
	sql += " order by m.parent_id, m.order_num"
	ids := make([]*int64, 0)
	err := r.DB.Raw(sql).Find(&ids).Error
	return ids, err
}

// 根据角色ID查询权限
func (r *SysMenuRepository) SelectMenuPermsByRoleId(roleId int64) []*string {
	sql := "select distinct IFNULL(m.perms, '') as perms from sys_menu m left join sys_role_menu rm on m.menu_id = rm.menu_id where m.status = '0' and rm.role_id = ?"
	list := make([]*string, 0)
	err := r.DB.Raw(sql, roleId).Scan(&list).Error
	if err != nil {
		return nil
	}
	return list
}
func (r *SysMenuRepository) SelectMenuPermsByUserId(userId int64) []*string {
	sql := "select distinct IFNULL(m.perms, '') as perms from sys_menu m left join sys_role_menu rm on m.menu_id = rm.menu_id left join sys_user_role ur on rm.role_id = ur.role_id left join sys_role r on r.role_id = ur.role_id where m.status = '0' and r.status = '0' and ur.user_id = ?"
	list := make([]*string, 0)
	err := r.DB.Raw(sql, userId).Scan(&list).Error
	if err != nil {
		return nil
	}
	return list
}
